//
//  IIIViewController.m
//  IIILocalizedIndexDemo
//
//  Created by sehone on 1/23/13.
//  Copyright (c) 2013 sehone. All rights reserved.
//

#import "IIIViewController.h"
#import "IIILocalizedIndex.h"

#import "TRFamousViewController.h"
#import "TRTabBarViewController.h"
#import "TRSearchView.h"
@interface IIIViewController ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *keys;
@property (strong, nonatomic) NSDictionary *data;

@property (strong, nonatomic) NSArray *oldKeys;
@property (strong, nonatomic) NSDictionary *oldData;


@property(strong,nonatomic)NSArray* receiveArray;

@property(strong,nonatomic)NSMutableDictionary * findIdbyNameDict;


@property(strong,nonatomic)NSArray * sendArray;
@property(copy,nonatomic)NSString * sendTitle;
@property(nonatomic,copy)NSString * famousID;

@property(nonatomic,strong)TRSearchView * searchView;

@property(nonatomic,assign)NSInteger isfirstComin;
@end

@implementation IIIViewController
@synthesize data = _data;


-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
    
}
- (void)initNavigation
{
    self.tabBarController.tabBar.hidden= NO;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    self.weChatNavigationBar.titleLabel.text=@"概念题材";
    self.weChatNavigationBar.rightButton.hidden=YES;
    [self.weChatNavigationBar.leftButton addTarget:self action:@selector(exit) forControlEvents:UIControlEventTouchUpInside];
    NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"TRSearchView" owner:self options:nil];
    self.searchView = nibObjects[0];
    self.searchView.bottom = self.weChatNavigationBar.bottom;
    self.searchView.height = self.weChatNavigationBar.height;
    [self.view addSubview:self.searchView];
    self.searchView.hidden = YES;
    [self.searchView.cancelBtn addTarget:self action:@selector(hideSearchView:) forControlEvents:UIControlEventTouchUpInside];
    [self.searchView.searBtn addTarget:self action:@selector(searchResult:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    [self.weChatNavigationBar.rightButton  addTarget:self action:@selector(search:) forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView.backgroundColor = [UIColor whiteColor];
}

- (void)exit
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)search:(id)btn{
    
    self.searchView.hidden = !self.searchView.hidden;
}

-(void)searchResult:(UIButton *)btn{
   // NSLog(@"搜索内容%@",self.searchView.textF.text);
    
    [self.searchView.textF resignFirstResponder];
    if (!self.findIdbyNameDict) {
        return;
    }
    
    NSMutableArray * rowChineseName = [@[]mutableCopy];
    for (NSDictionary * famousDict in self.receiveArray) {
        NSString * contentString =[[NSString replaceUnicode:famousDict.description] uppercaseString];
        NSString * keyString = [self.searchView.textF.text uppercaseString];
        NSLog(@"搜索内容：%@",contentString);
        if ([contentString rangeOfString:keyString].location !=NSNotFound) {
            [rowChineseName addObject:famousDict[@"NAME"]];
            [self.findIdbyNameDict setObject:famousDict forKey:famousDict[@"NAME"]];
        }
        
    }
    
    NSArray *arr = [NSArray arrayWithArray:rowChineseName];
    
    
    if (arr.count==0) {
        
        [SVProgressHUD showErrorWithStatus:@"没有相关内容"];
        return;
    }
    //保存一下旧的
    if (self.isfirstComin++==1) {
        self.oldData = _data;
        self.keys = _keys;
    }
    
    
    //汉字排序
    self.data = [IIILocalizedIndex indexed:arr];
    _keys = [self.data.allKeys sortedArrayUsingSelector:@selector(compare:)];
    [self.tableView reloadData];
}

-(void)hideSearchView:(UIButton *)btn{
    
    btn.superview.hidden = !btn.superview.hidden;
    
    if (btn.superview.hidden) {
        
        if (_oldData&&_oldData.count>0) {
            _data = self.oldData;
            _keys = self.keys;
            [self.tableView reloadData];
        }
        
    }
}
-(void)viewDidLoad{
    [super viewDidLoad];
    // Custom initialization
    self.isfirstComin = 1;
    //self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"main_bg"]];
    self.view.backgroundColor = [UIColor whiteColor];
    NSArray *arr = [self getData];
    self.data = [IIILocalizedIndex indexed:arr];
    self.keys = [self.data.allKeys sortedArrayUsingSelector:@selector(compare:)];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.contentInset = UIEdgeInsetsMake(23, 0, 0, 0);
  //  self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"main_bg"]];
  //  self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    if ([_tableView respondsToSelector:@selector(setSectionIndexColor:)]) {
        _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
        _tableView.sectionIndexTrackingBackgroundColor = [UIColor clearColor];
        self.tableView.separatorColor = [UIColor whiteColor];
    }
    [self initNavigation];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
    NSDictionary *params;
    
    
    if ([NSString isBlankString:ApplicationDelegate.markString]) {
        
        params=@{
                 TYPE:@"1009",
                 PRODUCT_TYPE_ORDER_FIELD:DIR_ORDER_FIELD_CREATEDATE,
                 PRODUCT_TYPE_ORDER_DIRECTION:DIR_ORDER_DIRECTION_ASC
                 };
        
    }else
    {
        params=@{
                 TYPE:@"1019",
                 PRODUCT_TYPE_ORDER_FIELD:DIR_ORDER_FIELD_CREATEDATE,
                 PRODUCT_TYPE_ORDER_DIRECTION:DIR_ORDER_DIRECTION_ASC,
                 BID:ApplicationDelegate.markString};
        
    }
    [QLMaskUtil showMaskLoadingWithView:self.tableView];
    [ApplicationDelegate.webAPI getWebAPIWithParams:params andMethodNode:NODE_DIRECTORY completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.tableView];
        NSString * message = responseObject[@"MESSAGE_INFO"][@"MESSAGE"];
        
        if ([responseObject[@"MESSAGE_INFO"][@"CODE"] isEqualToString:@"0000"]) {
            
            //名牌
            //按拼音排序好就放到数组，有section数组放pinyin首字母，row放内容，先排序好row,提取section
            
            if ([NSString isBlankString:ApplicationDelegate.markString]) {
                
            }
            self.receiveArray = responseObject[@"PACKAGE_RSP"][@"PACKAGE"];
            
            NSMutableArray * rowChineseName = [@[]mutableCopy];
            self.findIdbyNameDict = [@{}mutableCopy];
            for (NSDictionary * famousDict in self.receiveArray) {
                [rowChineseName addObject:famousDict[@"NAME"]];
                [self.findIdbyNameDict setObject:famousDict forKey:famousDict[@"NAME"]];
            }
            
            NSArray *arr = [NSArray arrayWithArray:rowChineseName];
            
            
            
            //汉字排序
            self.data = [IIILocalizedIndex indexed:arr];
            
            
            
            _keys = [self.data.allKeys sortedArrayUsingSelector:@selector(compare:)];
            
            
            
            //            NSLog(@"data:%@,\nkey:%@",[NSString replaceUnicode:[self.data description]],_keys);
            
            [self.tableView reloadData];
            
            
            [MMProgressHUD dismissWithSuccess:message];
        }else{
            [MMProgressHUD dismissWithError:message];
        }
        
        
    }];
    
    
    TRTabBarViewController * tabVC =(TRTabBarViewController*) self.tabBarController;
    
    self.tabBarController.tabBar.hidden =NO;
    tabVC.customTabBarView.hidden = NO;
    
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    if ([segue.identifier isEqualToString:@"TRFamousViewController"]) {
        TRFamousViewController* famousVC = segue.destinationViewController;
        
        famousVC.title = self.sendTitle;
        famousVC.famousID =self.famousID;
        
        
        
        
    }
}



#pragma mark - Table view controller data source & delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.keys.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    self.tableView.delegate = self;
    
    NSString *key = [self.keys objectAtIndex:section];
    NSArray *arr = [self.data objectForKey:key];
    return arr.count;
    
    
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    return [self.keys objectAtIndex:section];
   // return @"vvv";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"commonCell";
    UITableViewCell *cell;
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    int section = indexPath.section;
    int row = indexPath.row;
    
    
    NSArray *arr = [self.data objectForKey:[self.keys objectAtIndex:section]];
    cell.textLabel.text = [arr objectAtIndex:row];
 //   cell.textLabel.textColor = [UIColor whiteColor];
    
    cell.backgroundColor = [UIColor clearColor];
    
    
    UIView * colorView = [[UIView alloc]initWithFrame:CGRectMake(15, 33, 290, 1)];
    colorView.backgroundColor = [UIColor orangeColor];
    colorView.alpha = .7;
    [cell.contentView addSubview:colorView];
    return cell;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.keys;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel * v = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 20)];
    v.text = [self tableView:tableView titleForHeaderInSection:section];
    v.backgroundColor = [UIColor grayColor];
    return v;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20.0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *arr = [self.data objectForKey:[self.keys objectAtIndex:indexPath.section]];
    
    NSString * namePinpai = arr[indexPath.row];
    NSDictionary * p_id = self.findIdbyNameDict[namePinpai];
    
    self.sendTitle = namePinpai;
    self.famousID = p_id[@"ID"];
    TRFamousViewController *vc = [[TRFamousViewController alloc] init];
    vc.title = self.sendTitle;
    vc.famousID = self.famousID;
    [self.navigationController pushViewController:vc animated:YES];
}

# pragma mark - Data source

- (NSArray *)getData {
    NSArray * arr = @[];
    
    return arr;
}

@end
